<template>
  <div>
    <Form :label-width="120" ref="form1" :model="form1">
      <Row v-show="!switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="二级集团：" prop="twoLevelOrg">
            <Select v-model="form1.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="企业名称：" prop="orgId">
            <company-select v-model="form1.belongOrgName" style="width:100%"></company-select>
          </FormItem>
        </Col>
        <i-col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </i-col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="二级集团：" prop="twoLevelOrg">
            <Select v-model="form1.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="企业名称：" prop="orgId">
            <company-select v-model="form1.belongOrgName" style="width:100%"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业时间：" prop="workDate">
            <DatePicker type="daterange" v-model="form1.workDate" split-panels placeholder="请选择"
                        style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="作业单位：" prop="orgId">
            <Input type="text" v-model="form1.operateOrgName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="任务名称：" prop="planName">
            <Input type="text" v-model="form1.planName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button class="ivu-btn-add"  icon="md-cloud-download" :loading="buttonLoading" @click="exportData">导出</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :loading="loading" border :columns="columns1" :data="dataTable"
           width="100%" :height="tableHeight" highlight-row stripe size="small"
           @on-sort-change="onSortChange"></Table>
    <Row type="flex" justify="end">
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total
              show-sizer show-elevator/>
      </i-col>
    </Row>
  </div>
</template>

<script>

import companySelect from "../../../../components/company-select.vue"
import cascaderDom from "../../../../components/cascader-dom.vue"
import {Api} from '../../../../api/index.js'
import {sessionStorage, cookie} from '../../../../common/cacheUtils.js';

export default {
  components: {
    cascaderDom,companySelect
  },
  data() {
    return {
      userInfo: sessionStorage('userId').getObject('userId'),
      buttonLoading: false,
      twoLevelOrgs: [],
      loading: false,
      loading2: false,
      model1: false,
      rootOrgId: '',
      switchFlag: true,
      sortMap:{},
      form1: {workDate:["",""]},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns1: [
        {
          title: '序号',
          width: 100,
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 150,
          title: '任务名称',
          key: 'planName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '所属单位',
          key: 'belongOrgName',
          align: 'center'
        },
        {
          minWidth: 210,
          title: '作业单位',
          key: 'operateOrgName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业时间',
          key: 'workDate',
          align: 'center',
          sortable: 'custom',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.workDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          title: '操作',
          align: 'center',
          key: 'view',
          fixed: 'right',
          minWidth: 180,
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params.row, 1);
                  }
                }
              }, '查看'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: ((params.row.status == '0') && (params.row.operateOrgId == sessionStorage('userId').getObject('userId').currentOrgId || params.row.createUserId == sessionStorage('userId').getObject('userId').userId || this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId) || sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) ? '' : '#d0d0d0',
                  pointerEvents: ((params.row.status == '0') && (params.row.operateOrgId == sessionStorage('userId').getObject('userId').currentOrgId || params.row.createUserId == sessionStorage('userId').getObject('userId').userId || this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId) || sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.showData(params.row, 2);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: (params.row.permitSubmit == '1' && (params.row.status == '0') && (params.row.operateOrgId == sessionStorage('userId').getObject('userId').currentOrgId || params.row.createUserId == sessionStorage('userId').getObject('userId').userId || this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId) || sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) ? '' : '#d0d0d0',
                  pointerEvents: (params.row.permitSubmit == '1' && (params.row.status == '0') && (params.row.operateOrgId == sessionStorage('userId').getObject('userId').currentOrgId || params.row.createUserId == sessionStorage('userId').getObject('userId').userId || this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId) || sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据上报',
                      content: '<p>确定上报该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.reportWorkFlow(params.row);
                      },
                      cancelText: '取消'
                    });
                  }
                }
              }, '上报'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: ((params.row.status == '0') && (params.row.operateOrgId == sessionStorage('userId').getObject('userId').currentOrgId || params.row.createUserId == sessionStorage('userId').getObject('userId').userId || this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId) || sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) ? '' : '#d0d0d0',
                  pointerEvents: ((params.row.status == '0') && (params.row.operateOrgId == sessionStorage('userId').getObject('userId').currentOrgId || params.row.createUserId == sessionStorage('userId').getObject('userId').userId || this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId) || sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteData(params.row);
                      },
                      cancelText: '取消'
                    });
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
      currentOrgId: '',
      currentOrgName: '',
      setCurrentName: {},
      dataTable: [],
      add: false,
      ptwTypeList: [],
      workGradeList: [],
      tableHeight: 10,
      deleteRows: [],
      history: [],
      columns2: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
        },
        {
          width: 180,
          title: '审批时间',
          key: 'endTime',
          align: 'center',
        },
        {
          width: 185,
          title: '节点名称',
          key: 'name',
          align: 'center',
        },
        {
          width: 120,
          title: '审批人',
          key: 'userName',
          align: 'center'
        },
        {
          width: 100,
          title: '审批意见',
          key: 'route',
          align: 'center'
        },
        {
          width: 200,
          title: '备注',
          key: 'opinions',
          align: 'center'
        },
      ],
    }
  },
  mounted() {
    var currentTime = new Date();
    var threeMonthsAgo = new Date(currentTime.setMonth(currentTime.getMonth()-3));
    this.form1.workDate = [this.formatDate(threeMonthsAgo,"'yyyy-MM-dd'"),this.formatDate(new Date(),"'yyyy-MM-dd'")];
    this.queryTwoOrgInfo();
    this.rootOrgId = sessionStorage('userId').getObject('userId').orgInfo.parentId;
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    });
    this.query();
  },
  methods: {
    queryTwoOrgInfo() {
      if (sessionStorage('userId').getObject('userId').companyId != '18000000') {
        this.twoLevelOrgs.push({
          orgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
          orgName: sessionStorage('userId').getObject('userId').twoLevelOrgName
        });
      } else {
        this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
          this.twoLevelOrgs = res.data.data
        }).catch(e => {
        })
      }
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 44;
      } else {
        this.tableHeight = this.tableHeight + 44;
      }
    },
    closeWorkFlow() {

    },
    reportWorkFlow(row) {
      let userId = sessionStorage('userId').getObject('userId').userId;
      // 添加所属单位对应的二级集团
      this.$http.post(Api.startPtwTicketWorkFlow + '/' + row.planId + "/" + userId + '?twoLevelOrgId=' + row.twoLevelOrgId, {}).then((res) => {
        this.query();
      })
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100001', {params: {}}).then((res) => {
        this.ptwTypeList = res.data.data;
      })
      this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100003', {params: {}}).then((res) => {
        this.workGradeList = res.data.data;
      })
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },

    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    onSortChange(custom){
      console.log(custom)
      this.sortMap.sortKey = custom.key;
      this.sortMap.sortOrder = custom.order;
      this.query();
    },
    deleteData(row) {
      let url = Api.deletePtwPlan;
      this.$http.get(url, {params: {planId: row.planId}}).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    showHistory(row) {
      this.model1 = true;
      this.loading2 = true;
      this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
        this.history = res.data;
        this.loading2 = false;
        /*this.dataTable.map(item=>{
            if(item.procinstState =='0' || item.procinstState ==null){
                item.procinstStateName = '未上报';
            }else if(item.procinstState =='1'){
                item.procinstStateName = '已上报';
            }else if(item.procinstState =='2'){
                item.procinstStateName = '被退回';
            }else if(item.procinstState =='3'){
                item.procinstStateName = '已审批';
            }
        })
        this.pagedata.total = res.data.totalSize;*/
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    query() {
      this.loading = true;
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        userId: sessionStorage('userId').getObject('userId').userId
      }
      if (this.form1.workDate[0] != '' && this.form1.workDate[1] != '') {
        this.form1.workStartDate = this.formatDate(new Date(this.form1.workDate[0]), 'yyyy-MM-dd');
        this.form1.workEndDate = this.formatDate(new Date(this.form1.workDate[1]), 'yyyy-MM-dd');
      }else{
        this.form1.workStartDate = "";
        this.form1.workEndDate = "";
      }
      if (this.form1.belongOrgName == '' || this.form1.belongOrgName == undefined) {
        data.belongOrgName = sessionStorage('userId').getObject('userId').companyName
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data = Object.assign(data, JSON.parse(JSON.stringify(this.sortMap)));
      let url = Api.getPtwPlanList;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.loading = false;
        this.dataTable.forEach(item => {
          this.ptwTypeList.forEach(item1 => {
            if (item1.codingCodeId == item.ptwType)
              item.ptwTypeName = JSON.parse(JSON.stringify(item1.codingName));
            ;
          })
          this.workGradeList.forEach(item2 => {
            if (item2.codingCodeId == item.workGrade)
              item.workGradeName = item2.codingName;
          })
        })
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    exportData(){
      this.buttonLoading = true;
      let data = {
        userId: sessionStorage('userId').getObject('userId').userId
      }
      if (this.form1.workDate[0] != '' && this.form1.workDate[1] != '') {
        this.form1.workStartDate = this.formatDate(new Date(this.form1.workDate[0]), 'yyyy-MM-dd');
        this.form1.workEndDate = this.formatDate(new Date(this.form1.workDate[1]), 'yyyy-MM-dd');
      }else{
        this.form1.workStartDate = "";
        this.form1.workEndDate = "";
      }
      if (this.form1.belongOrgName == '' || this.form1.belongOrgName == undefined) {
        data.belongOrgName = sessionStorage('userId').getObject('userId').companyName
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data = Object.assign(data, JSON.parse(JSON.stringify(this.sortMap)));
      let url = Api.exportPtwPlanList;
      this.$http.get(url, {params: data,responseType: 'arraybuffer' }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "作业任务数据.xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.buttonLoading = false;
      }).catch(e => {
        this.buttonLoading = false;
        this.$Message.error("导出失败")
      })
    },
    reset() {
      this.form1 = {workDate: ["",""]};
      var currentTime = new Date();
      var threeMonthsAgo = new Date(currentTime.setMonth(currentTime.getMonth()-3));
      this.form1.workDate = [this.formatDate(threeMonthsAgo,"'yyyy-MM-dd'"),this.formatDate(new Date(),"'yyyy-MM-dd'")];
      this.query();
    },
    addInfo() {
      let obj = {};
      this.$router.push({name: 'ptwTicketEdit', params: {'data': obj}});
    },
    showData(data, flag) {
      if (flag == '1')
        this.$router.push({name: 'ptwTicketView', params: {'data': data}});
      else
        this.$router.push({name: 'ptwTicketEdit', params: {'data': data}});
    },
    cancel() {

    },
    formatDate(date, fmt) {
      if (typeof date == 'string') {
        return date;
      }
      if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
      if (!date || date == null) return null;
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return fmt
    },
  }
}
</script>
<style lang='css' scoped>
@import '../../../../index.css';
</style>
